import classNames from 'classnames'
import React from 'react'
import { useState, useEffect, useRef } from 'react'
import styles from './index.module.scss'
export default function Textarea({
  value,
  onChange,
  maxLength = 100,
  className,
  ...rest
}) {
  const [content, setContent] = useState(value || '')
  const handleChange = (e) => {
    setContent(e.target.value)
    onChange && onChange(e)
  }
  const inputRef = useRef(null)
  useEffect(() => {
    document
      .getElementById('topNode')
      .parentNode.parentNode.parentNode.addEventListener(
        'transitionend',
        function () {
          if (inputRef && inputRef.current) {
            function setSelectionRange(input, selectionStart, selectionEnd) {
              if (input.setSelectionRange) {
                input.focus()
                input.setSelectionRange(selectionStart, selectionEnd)
              } else if (input.createTextRange) {
                const range = input.createTextRange()
                range.collapse(true)
                range.moveEnd('character', selectionEnd)
                range.moveStart('character', selectionStart)
                range.select()
              }
            }
            setSelectionRange(
              inputRef.current,
              inputRef.current.value.length,
              inputRef.current.value.length
            )
          }
        }
      )
  }, [])
  return (
    <div className={styles.root} id="topNode">
      {/* 文本输入框 */}
      <textarea
        ref={inputRef}
        {...rest}
        className={classNames('textarea', className)}
        maxLength={maxLength}
        value={content}
        onChange={handleChange}
      />

      {/* 当前字数/最大允许字数 */}
      <div className="count">
        {content.length}/{maxLength}
      </div>
    </div>
  )
}
